<template>
    <div>
        <h1>拼团活动信息</h1>
        <!-- 查询 -->
        <div>
            <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
            >
                <el-form-item label="活动名称">
                    <el-input
                        v-model="searchForm.keyWord"
                        placeholder="活动名称"
                        clearable
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getGroupActiveList()"
                        >查询</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
        <el-button type="success" @click="showAddDiv()">发布拼团活动</el-button>
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="activeId" label="ID" />
            <el-table-column prop="activeName" label="活动名称" />
            <el-table-column prop="groupNum" label="拼团人数" />
            <el-table-column prop="beginTime" label="开始时间" />
            <el-table-column prop="endTime" label="截止时间" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button
                        type="primary"
                        :icon="Edit"
                        @click="showUpdateDiv(scope.row)"
                        circle
                    />
                    <el-button
                        type="danger"
                        @click="deleteActive(scope.row)"
                        :icon="Delete"
                        circle
                    />
                    <el-button
                        type="warning"
                        round
                        @click="JoinActive(scope.row)"
                        >参与</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div>
            <div class="demo-pagination-block">
                <el-pagination
                    v-model:current-page="searchForm.pageNum"
                    v-model:page-size="searchForm.pageSize"
                    :page-sizes="[100, 200, 300, 400]"
                    :size="size"
                    :disabled="disabled"
                    :background="background"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
        <!-- 活动修改 -->
        <div>
            <el-dialog
                v-model="dialogVisible"
                title="修改拼团活动信息"
                width="500"
            >
                <el-form
                    :model="form"
                    label-width="auto"
                    style="max-width: 600px"
                >
                    <el-form-item label="活动名称">
                        <el-input v-model="form.activeName" />
                    </el-form-item>
                    <el-form-item label="参团人数">
                        <el-input-number :min="1" v-model="form.groupNum" />
                    </el-form-item>
                    <el-form-item label="考试时间">
                        <el-date-picker
                            v-model="form.beginTime"
                            type="datetime"
                            placeholder="Select date and time"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                    <el-form-item label="终止时间">
                        <el-date-picker
                            v-model="form.endTime"
                            type="datetime"
                            placeholder="Select date and time"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogVisible = false"
                            >退出</el-button
                        >
                        <el-button type="primary" @click="updateGroupActive()">
                            保存
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <!-- 添加拼团活动 -->
        <div>
            <el-dialog
                v-model="dialogAddVisible"
                title="发布拼团活动"
                width="500"
            >
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="auto"
                >
                    <el-form-item label="活动名称" prop="activeName">
                        <el-input v-model="ruleForm.activeName" />
                    </el-form-item>
                    <el-form-item label="参团人数" prop="groupNum">
                        <el-input-number :min="1" v-model="ruleForm.groupNum" />
                    </el-form-item>
                    <el-form-item label="考试时间" prop="beginTime">
                        <el-date-picker
                            v-model="ruleForm.beginTime"
                            type="datetime"
                            placeholder="选择活动开始时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                    <el-form-item label="终止时间" prop="endTime">
                        <el-date-picker
                            v-model="ruleForm.endTime"
                            type="datetime"
                            placeholder="选择活动截止时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogAddVisible = false"
                            >关闭</el-button
                        >
                        <el-button
                            type="primary"
                            @click="submitForm(ruleFormRef)"
                        >
                            提交
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <!-- 参与活动 -->
        <div>
            <el-dialog
                v-model="dialogJoinVisible"
                title="参与活动弹出框"
                width="1000"
                label-width="auto"
            >
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 1100px"
                    :rules="joinRules"
                    :model="joinForm"
                    label-width="auto"
                    :inline="true"
                    class="demo-form-inline"
                >
                    <el-form-item label="拼团活动名称" prop="joinName">
                        <el-input
                            v-model="joinForm.joinName"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="拼团活动简介" prop="joinTip">
                        <el-input
                            type="textarea"
                            v-model="joinForm.joinTip"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="商品单位" prop="prodUnit">
                        <el-select
                            v-model="joinForm.prodUnit"
                            placeholder="请选择"
                            style="width: 150px"
                        >
                            <el-option
                                v-for="item in untiOptions"
                                :key="item.dictValue"
                                :label="item.dictName"
                                :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="活动轮播图" prop="images">
                        <el-upload
                            v-model:file-list="joinForm.images"
                            action="http://127.0.0.1:10010/group/join/uploadFile"
                            list-type="picture-card"
                            :headers="headers"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                        >
                            <el-icon><Plus /></el-icon>
                        </el-upload>

                        <el-dialog v-model="dialogimagesVisible">
                            <img
                                w-full
                                :src="dialogImageUrl"
                                alt="Preview Image"
                            />
                        </el-dialog>
                    </el-form-item>
                    <el-form-item label="活动开始时间">
                        <el-input
                            v-model="joinForm.beginTime"
                            readonly
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="活动截止时间">
                        <el-input
                            v-model="joinForm.endTime"
                            readonly
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="拼团时效">
                        <el-input-number
                            :min="1"
                            v-model="joinForm.expireTime"
                            style="width: 150px"
                        />
                    </el-form-item>
                    <el-form-item label="拼团人数">
                        <el-input-number
                            v-model="joinForm.groupNum"
                            readonly
                            style="width: 150px"
                        />
                    </el-form-item>
                    <el-form-item label="购买数量限制" prod="buyMax">
                        <el-input-number
                            :min="1"
                            v-model="joinForm.buyMax"
                            style="width: 150px"
                        />
                    </el-form-item>
                    <el-form-item label="补齐人数" prop="virtualNum">
                        <el-input-number
                            :min="0"
                            v-model="joinForm.virtualNum"
                            style="width: 150px"
                        />
                    </el-form-item>
                    <el-form-item label="商品原价" prop="prodPrice">
                        <el-input-number
                            :min="1"
                            v-model="joinForm.prodPrice"
                            style="width: 150px"
                        />
                    </el-form-item>
                    <el-form-item label="拼团价格" prop="groupPrice">
                        <el-input-number
                            :min="1"
                            v-model="joinForm.groupPrice"
                            style="width: 150px"
                        />
                    </el-form-item>
                    <el-form-item label="拼团商品" prop="prodInfoId">
                        <el-select
                            v-model="joinForm.prodInfoId"
                            placeholder="请选择"
                            style="width: 240px"
                        >
                            <el-option
                                v-for="item in prodInfoOptions"
                                :key="item.infoId"
                                :label="item.prodName"
                                :value="item.infoId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="配送方式" prop="sendKind">
                        <el-select
                            v-model="joinForm.sendKind"
                            placeholder="请选择"
                            style="width: 240px"
                        >
                            <el-option
                                v-for="item in kindOptinos"
                                :key="item.dictValue"
                                :label="item.dictName"
                                :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="运费设置" prop="sendPay">
                        <el-select
                            v-model="joinForm.sendPay"
                            placeholder="请选择"
                            style="width: 240px"
                        >
                            <el-option
                                v-for="item in payOptions"
                                :key="item.dictValue"
                                :label="item.dictName"
                                :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="运费" prop="sendMoney">
                        <el-input-number
                            :min="0"
                            v-model="joinForm.sendMoney"
                            style="width: 150px"
                        />
                    </el-form-item>
                    <el-form-item label="活动详情" prop="joinDesc">
                        <el-input
                            type="textarea"
                            v-model="joinForm.joinDesc"
                            style="width: 800px"
                        />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogJoinVisible = false"
                            >取消</el-button
                        >
                        <el-button
                            type="primary"
                            @click="submitJoinForm(ruleFormRef)"
                        >
                            提交
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import type { ComponentSize } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import {
    selectGroupActiveService,
    addGroupActiveService,
    deleteGroupActiveService,
    updateGroupActiveService,
} from "../api/group/group";
import { addGroupJoinService } from "../api/group/join";
import { selectProdInfoService, selectDictByService } from "../api/prod";

const headers = ref({
    token: sessionStorage.getItem("token"),
});

const dialogVisible = ref(false);
const dialogAddVisible = ref(false);
const dialogJoinVisible = ref(false);
const tableData = ref([]);
const searchForm = ref({
    beginTime: "",
    endTime: "",
    keyWord: "",
    maxValue: 0,
    minValue: 0,
    pageNum: 1,
    pageSize: 3,
    statusId: 0,
    typeId: 0,
});

const form = ref({
    activeId: 0,
    activeName: "",
    beginTime: "",
    endTime: "",
    groupNum: 1,
});

const joinForm = ref({
    activeId: 0,
    beginTime: "",
    buyMax: null,
    createBy: "",
    createTime: "",
    endTime: "",
    expireTime: null,
    groupNum: null,
    groupPrice: null,
    joinDesc: "",
    joinId: 0,
    joinImages: "",
    prodImages: [],
    joinName: "",
    joinTip: "",
    joinTop: 1,
    prodInfoId: null,
    prodPrice: null,
    prodUnit: null,
    sendKind: null,
    sendMoney: null,
    sendPay: null,
    virtualNum: null,
    images: [],
});

const JoinActive = (row: any) => {
    joinForm.value = {
        activeId: 0,
        beginTime: row.beginTime,
        buyMax: null,
        endTime: row.endTime,
        expireTime: null,
        groupNum: row.groupNum,
        groupPrice: null,
        prodImages: [],
        joinDesc: "",
        joinId: 0,
        joinImages: "",
        joinName: "",
        joinTip: "",
        joinTop: 1,
        prodInfoId: null,
        prodPrice: null,
        prodUnit: null,
        sendKind: null,
        sendMoney: null,
        sendPay: null,
        virtualNum: null,
        images: [],
    };
    dialogJoinVisible.value = true;
};

const showUpdateDiv = (row: any) => {
    form.value = row;
    dialogVisible.value = true;
};

const dialogImageUrl = ref("");
const dialogimagesVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogimagesVisible.value = true;
};

const deleteActive = (row: any) => {
    ElMessageBox.confirm("删除数据后无法恢复,您确定要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            // 确认删除
            deleteGroupActiveService(row).then((res) => {
                if (res.data.flag) {
                    ElMessage.success("删除成功");
                    getGroupActiveList();
                } else {
                    ElMessage.error(res.data.smg);
                }
            });
        })
        .catch(() => {
            // 取消删除
        });
};

const updateGroupActive = () => {
    updateGroupActiveService(form.value).then((res) => {
        if (res.data.flag) {
            ElMessage.success("修改成功");
            dialogVisible.value = false;
            getGroupActiveList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

const showAddDiv = () => {
    ruleForm.value = {
        activeId: 0,
        activeName: "",
        beginTime: "",
        endTime: "",
        groupNum: 1,
    };
    dialogAddVisible.value = true;
};

const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
    activeId: 0,
    activeName: "",
    beginTime: "",
    endTime: "",
    groupNum: 1,
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules>({
    activeName: [
        { required: true, message: "请输入活动名称", trigger: "blur" },
    ],
    groupNum: [
        { required: true, message: "请输入活动拼团名称", trigger: "blur" },
    ],
    beginTime: [{ required: true, message: "请输入起始时间", trigger: "blur" }],
    endTime: [{ required: true, message: "请输入终止时间", trigger: "blur" }],
});

const joinRules = reactive<FormRules>({
    joinName: [
        { required: true, message: "请输入拼团活动名称", trigger: "blur" },
    ],
    joinTip: [{ required: true, message: "请输入活动简介", trigger: "blur" }],
    prodUnit: [{ required: true, message: "请输入商品单位", trigger: "blur" }],
    images: [{ required: true, message: "请输入商品轮播图", trigger: "blur" }],
    buyMax: [
        { required: true, message: "请输入商品购买极限", trigger: "blur" },
    ],
    virtualNum: [
        { required: true, message: "请输入补齐人数", trigger: "blur" },
    ],
    prodPrice: [{ required: true, message: "请输入商品原价", trigger: "blur" }],
    groupPrice: [
        { required: true, message: "请输入拼团价格", trigger: "blur" },
    ],
    prodInfoId: [
        { required: true, message: "请选择拼团商品", trigger: "blur" },
    ],
    sendKind: [{ required: true, message: "请选择配送方式", trigger: "blur" }],
    sendPay: [{ required: true, message: "请选择运费设置", trigger: "blur" }],
    sendMoney: [{ required: true, message: "请输入输入运费", trigger: "blur" }],
    joinDesc: [{ required: true, message: "请输入活动详情", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            addGroupActiveService(ruleForm.value).then((res) => {
                if (res.data.flag) {
                    ElMessage.success("添加成功");
                    dialogAddVisible.value = false;
                    getGroupActiveList();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};
const submitJoinForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            joinForm.value.images.forEach((item) => {
                joinForm.value.prodImages.push(item.response.data);
            });
            addGroupJoinService(joinForm.value).then((res) => {
                if (res.data.flag) {
                    ElMessage.success("参与成功");
                    dialogJoinVisible.value = false;
                    getGroupActiveList();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));

const total = ref(0);
const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);

const handleSizeChange = (val: number) => {
    searchForm.value.pageSize = val;
    getGroupActiveList();
};
const handleCurrentChange = (val: number) => {
    searchForm.value.pageNum = val;
    getGroupActiveList();
};

const getGroupActiveList = () => {
    selectGroupActiveService(searchForm.value).then((res) => {
        if (res.data.flag) {
            tableData.value = res.data.data.records;
            total.value = res.data.data.total;
        }
    });
};
const prodInfoOptions = ref([]);
const getProdInfoList = () => {
    selectProdInfoService().then((res) => {
        if (res.data.flag) {
            prodInfoOptions.value = res.data.data;
        }
    });
};

const untiOptions = ref([]);
const getUnitList = () => {
    selectDictByService(2).then((res) => {
        if (res.data.flag) {
            untiOptions.value = res.data.data;
        }
    });
};
const kindOptinos = ref([]);
const getKindList = () => {
    selectDictByService(15).then((res) => {
        if (res.data.flag) {
            kindOptinos.value = res.data.data;
        }
    });
};
const payOptions = ref([]);
const getPayList = () => {
    selectDictByService(16).then((res) => {
        if (res.data.flag) {
            payOptions.value = res.data.data;
        }
    });
};

onMounted(() => {
    getGroupActiveList();
    getProdInfoList();
    getUnitList();
    getKindList();
    getPayList();
});

import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
} from "@element-plus/icons-vue";
</script>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
    margin-top: 10px;
}
.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>
